package com.gzhryc.shared_device.bxscn.code.dao;

import com.gzhryc.jdbc.BaseDao;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.Query;
import com.gzhryc.jdbc.models.Parameters;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyBattery;
import com.gzhryc.shared_device.bxscn.code.dao.models.PortableEnergyBatteryPlaceCount;
import com.gzhryc.shared_device.bxscn.code.dao.models.PortableEnergyBatteryTypeCount;

import java.sql.SQLException;
import java.util.List;

public class PortableEnergyBatteryDao extends BaseDao<PortableEnergyBattery>{

    public PortableEnergyBatteryDao(String jdbcKey) {
        super(jdbcKey);
    }

    public List<PortableEnergyBatteryTypeCount> groupTypeByConditions(Conditions conditions) throws SQLException {
        String sql = "SELECT type AS batteryType,COUNT(1) AS deviceCount FROM " + this.tableName;
        Query query = new Query(sql);
        query.appendSql(conditions.toSql(query.getParams(),true));
        query.appendSql(" GROUP BY type");
        return this.jdbcHelper.find(query,PortableEnergyBatteryTypeCount.class);
    }

    public List<PortableEnergyBatteryPlaceCount> groupPlaceByConditions(Conditions conditions) throws SQLException {
        String sql = "SELECT place_id AS placeId,COUNT(1) AS deviceCount FROM " + this.tableName;
        Query query = new Query(sql);
        query.appendSql(conditions.toSql(query.getParams(),true));
        query.appendSql(" GROUP BY place_id");
        return this.jdbcHelper.find(query,PortableEnergyBatteryPlaceCount.class);
    }

    public List<Long> findOnlyPlaceIdByConditions(Conditions conditions,Integer pageNo,Integer pageLimit) throws SQLException {
        String sql = "SELECT DISTINCT place_id FROM " + this.tableName;
        Query query = new Query(sql);
        query.appendSql(conditions.toSql(query.getParams(),true));
        query.setPageNo(pageNo);
        query.setPageLimit(pageLimit);
        return this.jdbcHelper.findFirstField(query,Long.class);
    }

    public List<String> findOnlyBatteryTypeByConditions(Conditions conditions) throws SQLException {
        String sql = "SELECT DISTINCT type FROM " + this.tableName;
        Query query = new Query(sql);
        query.appendSql(conditions.toSql(query.getParams(),true));
        return this.jdbcHelper.findFirstField(query,String.class);
    }

    public int updateDeviceSn(String newDeviceSn,String oldDeviceSn) throws SQLException {
        String sql = "UPDATE " + this.tableName + " SET device_sn = ? WHERE device_sn = ?";
        Parameters prams = new Parameters();
        prams.setObject(newDeviceSn);
        prams.setObject(oldDeviceSn);
        return this.jdbcHelper.update(sql,prams);
    }
}
